<template>
  <div class="goods-list">
    <el-card>
      <div class="header" slot="header">商品列表</div>
      <div class="card-body">
        <!-- 条件查询商品 -->
        <!-- 条件查询 -->
        <el-form
          :inline="true"
          class="demo-form-inline"
          :model="searchData"
          ref="searchFormData"
          size="small"
        >
          <el-form-item label="商品名称">
            <el-input
              placeholder="商品名称"
              v-model="searchData.productName"
            ></el-input>
          </el-form-item>
          <el-form-item label="供应商名称">
            <el-input
              placeholder="供应商名称"
              v-model="searchData.supplier"
            ></el-input>
          </el-form-item>
          <el-form-item label="供应商电话">
            <el-input
              placeholder="供应商电话"
              v-model="searchData.phone"
            ></el-input>
          </el-form-item>
          <el-form-item label="进货价">
            <el-input
              placeholder="进货价"
              v-model="searchData.costPrice"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-cascader
              v-model="searchData.productCategoryId"
              :options="options"
              :show-all-levels="false"
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
        <!-- 商品列表的表格 -->
        <el-table
          fit
          :data="goodsDatas"
          stripe
          highlight-current-row
          :style="{ width: tableWidth + 'px' }"
        >
          <el-table-column label="商品名称">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.productName }}</span>
              <el-input
                v-else
                size="small"
                v-model="scope.row.productName"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="productCategoryName" label="所属分类">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit"
                >{{ scope.row.productCategoryName }}
              </span>
              <el-cascader
                v-else
                size="small"
                v-model="scope.row.productCategoryId"
                :options="options"
                :show-all-levels="false"
              ></el-cascader>
            </template>
          </el-table-column>
          <el-table-column label="供应商名称">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.supplier }}</span>
              <el-input
                v-else
                size="small"
                v-model="scope.row.supplier"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="供应商电话">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.phone }}</span>
              <el-input
                v-else
                size="small"
                v-model="scope.row.phone"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="进货价">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.costPrice }}</span>
              <el-input
                v-else
                size="small"
                v-model="scope.row.costPrice"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="销售价">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.salePrice }}</span>
              <el-input
                v-else
                size="small"
                v-model="scope.row.salePrice"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="添加时间">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.createTime }}</span>
              <el-date-picker
                v-else
                size="small"
                v-model="scope.row.createTime"
                type="datetime"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="更新时间">
            <template slot-scope="scope">
              <span>{{ scope.row.updateTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产日期">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.produceTime }}</span>
              <el-date-picker
                v-else
                size="small"
                v-model="scope.row.produceTime"
                type="datetime"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="过期日期">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.expireTime }}</span>
              <el-date-picker
                v-else
                size="small"
                v-model="scope.row.expireTime"
                type="datetime"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :type="scope.row.isEdit ? 'success' : ''"
                @click="handleEdit(scope.row)"
              >
                {{ scope.row.isEdit ? "完成" : "编辑" }}
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="primary"
                @click="addInventory(scope.row)"
                >库存</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加库存 -->
    <el-dialog
      class="category-dialog"
      title="添加商品库存"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="updateForm"
        label-width="120px"
        class="inventory-add-form"
        :rules="rules"
        ref="inventoryForm"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-input
            v-model="updateForm.product_name"
            placeholder="商品名称"
            readonly
          ></el-input>
        </el-form-item>
        <el-input v-model="updateForm.product_id" type="hidden"></el-input>
        <el-form-item label="库存数据量" prop="quantity">
          <el-input
            v-model="updateForm.quantity"
            placeholder="库存数据量"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addInventoryData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 需要导入查询商品分类的数据接口
import {
  getAllCategory,
  getGoods,
  deleteGoodsById,
  //addGoods,
  updateGoods,
} from "@/api/Goods";
import { addGoodsInventory, getInventoryByGoodsID } from "@/api/inventory";
import { mapState } from "vuex";
import dayjs from "dayjs";
export default {
  data() {
    return {
      updateForm: {
        product_id: "",
        product_name: "",
        quantity: "",
      },
      rules: {
        quantity: {
          required: true,
          message: "请输入库存数量",
          trigger: "blur",
        },
      },
      dialogFormVisible: false,
      // 条件搜索中的商品分类下拉数据
      options: [],
      //  搜索的数据
      searchData: {
        productName: "",
        supplier: "",
        phone: "",
        costPrice: "",
        productCategoryId: "",
      },
      //   商品表格
      goodsDatas: [],

      // 表格的宽度
      tableWidth: 0,
      //   分页数据
      pageSize: 5,
      total: 10,
      currentPage: 1,
    };
  },
  methods: {
    // 搜索提交的按钮点击时触发的事件
    onSubmit() {
      // this.searchData.product_category_id =
      //   this.searchData.product_category_id.length === 1
      //     ? this.searchData.product_category_id[0]
      //     : this.searchData.product_category_id[1];
      this.getGoodsData();
    },
    // 分页size变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getGoodsData();
    },
    // 分页page变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getGoodsData();
    },

    // 删除商品数据
    handleDelete(row) {
      deleteGoodsById(row.id).then((resp) => {
        if (resp.data.code == 20000) {
          this.getGoodsData();
        }
      });
    },
    // 弹出库存添加的对话框
    addInventory(row) {
      // 先判断当前这个商品对应有没有库存
      getInventoryByGoodsID({ id: row.id }).then((resp) => {
        if (resp.data.code === 20001) {
          this.updateForm.product_id = row.id;
          this.updateForm.product_name = row.product_name;
          this.dialogFormVisible = true;
        } else {
          this.$message({
            message: row.product_name + "库存已存在，请到库存管理操作",
            type: "error",
          });
        }
      });
    },
    // 提交库存数据
    addInventoryData() {
      this.$refs.inventoryForm.validate((data) => {
        if (data) {
          addGoodsInventory(this.updateForm).then((resp) => {
            if (resp.data.code == 20000) {
              this.dialogFormVisible = false;
              this.$router.push("/inventory/InventoryList");
            }
          });
        }
      });
    },
    // 修改商品数据
    handleEdit(row) {
      // 保留当前未修改前的商品分类的id
      let old_product_category_id = row.productCategoryId;
      // 根据标记来确定表格是编辑状态，还是文本状态
      row.isEdit = !row.isEdit;
      if (!row.isEdit) {
        if (Array.isArray(row.productCategoryId)) {
          row.productCategoryId =
            row.productCategoryId.length === 1
              ? row.productCategoryId[0]
              : row.productCategoryId[1];
        } else {
        row.productCategoryId = old_product_category_id;
        }

        // 需要对提交的日期时间格式数据进行统一处理
        row.createTime = dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss");
        console.log(row.createTime);
        row.updateTime = dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss");
        row.produceTime = dayjs(row.produceTime).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        row.expireTime = dayjs(row.expireTime).format("YYYY-MM-DD HH:mm:ss");

        updateGoods(row).then((resp) => {
          if (resp.data.code == 20000) {
            this.getGoodsData();
          }
        });
      }
    },
    // 查询所有商品分类数据
    loadGoodsAllCategory() {
      getAllCategory().then((resp) => {
        let respData = resp.data;
        if (respData.code == 20000) {
          respData.data.forEach((v) => {
            let category = {};
            category.value = v.id;
            category.label = v.categoryName;

            if (v.children.length > 0) {
              let subCategory = [];
              v.children.forEach((vv) => {
                subCategory.push({
                  value: vv.id,
                  label: vv.categoryName,
                });
              });
              category.children = subCategory;
            }
            this.options.push(category);
          });
        }
      });
    },
    // 加载商品数据
    getGoodsData() {
      getGoods(
        this.currentPage,
        this.pageSize,
        this.searchData,
      ).then((resp) => {
        let respData = resp.data;
        if (respData.code == 20000) {
          //给页面的表格数据的每行添加一个标记
          respData.data.rows.forEach((v) => {
            v.isEdit = false;
          });
          this.goodsDatas = respData.data.rows;
          this.total = respData.data.total;
        }
      });
    },
    // 计算表格需要的实际宽度
    resizeTableWidth() {
      this.tableWidth = screen.availWidth - 300;
    },
  },
  // 计算属性
  computed: {
    ...mapState(["isCollapse"]),
  },
  created() {
    this.loadGoodsAllCategory();
    this.getGoodsData();
    this.resizeTableWidth();
  },
};
</script>

<style lang="less" scoped>
.goods {
  width: 100%;
  height: 100%;
}
/deep/ .el-dialog {
  width: 600px;
  .el-input {
    width: 440px;
  }
}
</style>
